{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "df9e35ac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"model_5\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " input_6 (InputLayer)        [(None, 28, 28, 1)]       0         \n",
      "                                                                 \n",
      " conv2d_12 (Conv2D)          (None, 28, 28, 32)        320       \n",
      "                                                                 \n",
      " max_pooling2d_9 (MaxPooling  (None, 27, 27, 32)       0         \n",
      " 2D)                                                             \n",
      "                                                                 \n",
      " conv2d_13 (Conv2D)          (None, 27, 27, 64)        18496     \n",
      "                                                                 \n",
      " max_pooling2d_10 (MaxPoolin  (None, 26, 26, 64)       0         \n",
      " g2D)                                                            \n",
      "                                                                 \n",
      " flatten_5 (Flatten)         (None, 43264)             0         \n",
      "                                                                 \n",
      " dense_10 (Dense)            (None, 256)               11075840  \n",
      "                                                                 \n",
      " dense_11 (Dense)            (None, 10)                2570      \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 11,097,226\n",
      "Trainable params: 11,097,226\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "None\n",
      "Epoch 1/5\n",
      "118/118 [==============================] - 281s 2s/step - loss: 0.1974 - acc: 0.9385\n",
      "Epoch 2/5\n",
      "118/118 [==============================] - 278s 2s/step - loss: 0.0458 - acc: 0.9861\n",
      "Epoch 3/5\n",
      "118/118 [==============================] - 290s 2s/step - loss: 0.0281 - acc: 0.9914\n",
      "Epoch 4/5\n",
      "118/118 [==============================] - 283s 2s/step - loss: 0.0202 - acc: 0.9936\n",
      "Epoch 5/5\n",
      "118/118 [==============================] - 303s 3s/step - loss: 0.0149 - acc: 0.9951\n",
      "20/20 [==============================] - 15s 679ms/step - loss: 0.0324 - acc: 0.9898\n",
      "[0.0323878712952137, 0.989799976348877]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import tensorflow.keras.datasets.mnist as mnist\n",
    "\n",
    "(x_train, y_train), (x_test, y_test) = mnist.load_data() \n",
    "x_train, x_test = x_train / 255.0, x_test / 255.0           \n",
    "# 数据，扩展维度\n",
    "x_train = tf.expand_dims(x_train,-1)    \n",
    "x_test = tf.expand_dims(x_test,-1)\n",
    "# 标签\n",
    "y_train = np.float32(tf.keras.utils.to_categorical(y_train,num_classes=10))  # one-hot处理\n",
    "y_test = np.float32(tf.keras.utils.to_categorical(y_test,num_classes=10))\n",
    "bacth_size = 512\n",
    "train_dataset = tf.data.Dataset.from_tensor_slices((x_train,y_train)).batch(bacth_size).shuffle(bacth_size * 10)\n",
    "test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(bacth_size)\n",
    "\n",
    "\n",
    "# 创建模型\n",
    "input_xs = tf.keras.Input([28,28,1])\n",
    "conv = tf.keras.layers.Conv2D(32,3,padding=\"SAME\", activation=tf.nn.relu)(input_xs)# 卷积层 \n",
    "conv = tf.keras.layers.MaxPool2D(strides=[1,1])(conv) # 池化层\n",
    "conv = tf.keras.layers.Conv2D(64,3,padding=\"SAME\", activation='relu')(conv)# 卷积层\n",
    "conv = tf.keras.layers.MaxPool2D(strides=[1,1])(conv) # 池化层\n",
    "flat = tf.keras.layers.Flatten()(conv) \n",
    "dense = tf.keras.layers.Dense(256, activation=tf.nn.relu)(flat) # 全连接层\n",
    "logits = tf.keras.layers.Dense(10, activation='softmax')(dense) # 全连接层 \n",
    "model = tf.keras.Model(inputs=input_xs, outputs=logits) # 创建模型model\n",
    "print(model.summary())\n",
    "\n",
    "model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])\n",
    "model.fit(train_dataset, epochs=5)\n",
    "# 模型在测试集上的评估\n",
    "score = model.evaluate(test_dataset)\n",
    "print(score)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59d69bd6",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
